<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>几种错误的捕获方式</title>
  </head>
  <body>
    <img src="1.xxxxx" alt="" />
    <script>
      /* 1.try catch 只能捕获同步的代码错误
      setTimeout(() => {
        try {
          throw new Error("error");
        } catch (err) {
          console.log("err", err);
        }
      }, 1000);

      try {
        setTimeout(() => {
          throw new Error("error2");
        }, 1000);
      } catch (err) {
        console.log("err", err);
      } */

      /* 2.window.onerror 可以捕获同步代码和异步代码的错误，但是不能捕获资源加载的错误
      //   setTimeout(() => {
      //     throw new Error("error3");
      //   }, 1000);
      //   window.onerror = function (...args) {
      //     console.log("window.onerror", args);
      //   }; */

      /* 3.window.addEventListener("error",callback,true) 可以捕获资源加载的错误 , 也能捕获同步和异步代码的错误，但是不呢捕获promise的错误
      window.addEventListener(
        "error",
        function (...args) {
          //   console.log("window.addEventListener", arguments);
          console.log("window.addEventListener", args);
        },
        true
      ); */

      /* window.addEventListener("unhandledrejection",callback,true) 可以捕获promise的错误
      const p = new Promise((resolve, reject) => {
        reject("error5");
      });

      const asyncFn = async () => {
        await p;
      };
      //   .catch((err) => {
      //     console.log("promise-err", err);
      //   });

      window.addEventListener("error", function (ev) {
        console.log("ev", ev);
      });

      window.addEventListener("unhandledrejection", function (ev) {
        console.log("unhandledrejection", ev);
        throw ev.reason; */

      //  最佳实践是在window.addEventListener("unhandledrejection", callback, true)中抛出错误，然后在window.addEventListener("error", callback, true)中捕获错误
    </script>
  </body>
</html>
